package com.inspur.dgov.vlbod.service.impl;

import com.inspur.dgov.vlbod.secure.constant.SecureConstant;
import com.inspur.dgov.vlbod.secure.token.TokenFactory;
import com.inspur.dgov.vlbod.secure.token.UserRecord;
import com.inspur.dgov.vlbod.service.UserRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserRecordServiceImpl implements UserRecordService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${dgov.auth.disable:false}")
    private Boolean disableAuth;

    @Value("${dgov.auth.default-userid:test}")
    private String defaultUserId;

    @Value("${dgov.auth.default-organid:test}")
    private String defaultOrganId;

    @Override
    public UserRecord getUserRecord(HttpServletRequest request) {
        UserRecord record = null;
        if(!disableAuth){
            String authorization = request.getHeader(SecureConstant.BASIC_HEADER_KEY);
            if (null != authorization && !"".equals(authorization)) {
                Object userObj = this.redisTemplate.opsForValue().get(SecureConstant.TOKEN_USER_KEY + authorization);
                if (null != userObj) {
                    record = (UserRecord) userObj;
                } else {
                    record = TokenFactory.getUserRecordFromToken(authorization);
                }
            }
        }else{
            record = new UserRecord();
            record.setUserId(defaultUserId);
            record.setOrganCode(defaultOrganId);
        }
        return record;
    }
}
